package Pet.Management.repository;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import Pet.Management.domain.entity.Comment;

@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
    
    /**
     * 查询指定帖子的顶级评论
     */
    @Query("SELECT c FROM Comment c WHERE c.post.id = :postId AND c.parent IS NULL AND c.delFlag = false ORDER BY c.createTime DESC")
    Page<Comment> findRootCommentsByPostId(@Param("postId") Long postId, Pageable pageable);
    
    /**
     * 查询指定评论的回复
     */
    @Query("SELECT c FROM Comment c WHERE c.parent.id = :parentId AND c.delFlag = false ORDER BY c.createTime ASC")
    List<Comment> findRepliesByParentId(@Param("parentId") Long parentId);
    
    /**
     * 查询指定用户的评论
     */
    @Query("SELECT c FROM Comment c WHERE c.user.id = :userId AND c.delFlag = false ORDER BY c.createTime DESC")
    Page<Comment> findByUserId(@Param("userId") Long userId, Pageable pageable);
    
    /**
     * 更新评论点赞数
     */
    @Modifying
    @Query("UPDATE Comment c SET c.likeCount = c.likeCount + :delta WHERE c.id = :commentId")
    void updateLikeCount(@Param("commentId") Long commentId, @Param("delta") int delta);
    
    /**
     * 根据帖子ID计算评论总数
     */
    @Query("SELECT COUNT(c) FROM Comment c WHERE c.post.id = :postId AND c.delFlag = false")
    Long countByPostId(@Param("postId") Long postId);
} 